import { Module } from 'vuex'
import api from '@/api/config'

interface UserState {
  token: string | null
  username: string
  email: string
}

const user: Module<UserState, any> = {
  namespaced: true,
  
  state: {
    token: localStorage.getItem('token'),
    username: '',
    email: ''
  },
  
  mutations: {
    SET_TOKEN(state, token: string) {
      state.token = token
      localStorage.setItem('token', token)
    },
    SET_USER_INFO(state, { username, email }) {
      state.username = username
      state.email = email
    },
    CLEAR_USER(state) {
      state.token = null
      state.username = ''
      state.email = ''
      localStorage.removeItem('token')
    }
  },
  
  actions: {
    async login({ commit }, { username, password }) {
      try {
        const response = await api.post('/login', {
          username,
          password
        })
        
        const { token } = response
        commit('SET_TOKEN', token)
        // 由于后端没有返回用户信息，这里需要额外请求
        const userInfo = await api.get('/user/info')
        commit('SET_USER_INFO', userInfo)
      } catch (error) {
        throw new Error('登录失败')
      }
    },
    
    async register({ commit }, { username, password, email }) {
      try {
        await api.post('/register', {
          username,
          password,
          email
        })
      } catch (error) {
        throw new Error('注册失败')
      }
    },
    
    logout({ commit }) {
      commit('CLEAR_USER')
    }
  }
}

export default user 